package com.wangbl.manager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

import com.wangbl.manager.model.DevInfo;
import com.wangbl.manager.utils.Logger;

public class Controller {

	private static final String TAG = "Controller";
	private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
			.getDefaultAdapter();
	private BluetoothSocket socket;
	private InputStream in;
	private OutputStream out;

	public boolean connect(DevInfo info) {
		Logger.i(TAG, "connect");
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(info
				.getMac());
		try {
			socket = device.createRfcommSocketToServiceRecord(UUID
						.fromString("00001101-0000-1000-8000-00805F9B34FB"));
			socket.connect();
			in = socket.getInputStream();
			out = socket.getOutputStream();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean write(String msg) {
		Logger.i(TAG, "write:" + msg);
		try {
			Logger.i(TAG, "isConnected:" + socket.isConnected());
			if (socket != null && socket.isConnected()) {
				out.write(msg.getBytes());
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public void sendMessage() {

	}

	public boolean disconntect() {
		if (socket != null) {
			try {
				socket.close();
				return true;
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}

		return true;
	}

}
